package org.tmall.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.spi.DirStateFactory.Result;

import com.mysql.jdbc.Driver;

public class BaseDao {
	private static final String driverClass = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/tmall?useUnicode=true&characterEncoding=utf-8";
	private static final String user = "root";
	private static final String password = "root";
	
	/**
	 * 加载jdbc驱动
	 */
	static {
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 鑾峰彇鏁版嵁搴撹繛鎺�
	 * @return
	 */
	public Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url,user,password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 鎵ц鏌ヨ璇彞
	 * @param sql
	 * @param params
	 * @return
	 */
	public ResultSet executeQuery(String sql, Object...params) {
		Connection conn = this.getConnection();
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			if(params != null && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i+1, params[i]);
				}
			}
			
			return pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public int executeUpdate(String sql, Object...params) {
		Connection conn = this.getConnection();
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
			if(params != null && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i+1, params[i]);
				}
			}
			return pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll(null, pstmt, conn);
		}
		return 0;
	}
	
	public void closeAll(ResultSet rs, Statement stmt, Connection conn) {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if(conn != null && conn.isClosed() == false) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} 
	}
}





